<?php
/**
 * Created by PhpStorm.
 * User: Frings
 * Date: 2017/4/27
 * Time: 10:51
 */

namespace app\models;

use Yii;
use app\librarys\DbCacheUtility;
use yii\web\Cookie;
use yii\db\Query;
use app\models\db\Manager as ManagerDb;
use app\models\db\ManagerRoleRelation;
use app\models\db\Role;

class Manager
{
    const SessionKey = 'session_key_manager';
    const CookieKey = 'cookie_key_manager';

    /**
     * 获取当前登录用户(如果为null,则未登录)
     * @return mixed|null
     */
    public static function getCurrentManager()
    {
        if (\Yii::$app->session->has(self::SessionKey)) {
            return \Yii::$app->session->get(self::SessionKey);
        }

//        if (YII_ENV == 'dev') {
//            //调试用---begin
//            $currentManager = self::validatePassword('admin', '1');
//            self::setCurrentManager($currentManager);
//            return $currentManager;
//            //-----end
//        }

        return null;
    }

    /**
     * 计算管理员列表数量
     * @param $name
     * @param $account
     * @param $phone
     * @param int $role_id
     * @modify add role_id by milloc 2018-4-27
     * @return false|null|string
     */
    public static function getManagerCount($name, $account, $phone, $role_id)
    {
        // $sql = 'SELECT COUNT(*) FROM t_manager m WHERE name LIKE :name AND account LIKE :account AND phone LIKE :phone AND is_deleted = 0';
        // $cmd = \Yii::$app->db->createCommand($sql);
        // $cmd->bindValue(':name', '%' . $name . '%');
        // $cmd->bindValue(':account', '%' . $account . '%');
        // $cmd->bindValue(':phone', '%' . $phone . '%');

        // $result = DbCacheUtility::queryScalar($cmd);
        // return $result;

        $query = (new Query)->from(['m' => ManagerDb::tableName()])->where(['m.is_deleted' => ManagerDb::IS_DELETED_NO])->andFilterWhere(['like', 'm.name', $name])->andFilterWhere(['like', 'm.account', $account])->andFilterWhere(['like', 'm.phone', $phone]);

        if ($role_id) {
            if (Role::find(['id' => $role_id, 'is_deleted' => Role::IS_DELETED_NO])->count()) {
                $query = $query->leftJoin(['r' => ManagerRoleRelation::tableName()], 'r.manager_id = m.id')->andWhere(['r.role_id' => $role_id]);
            } else {
                return 0;
            }
        }

        $res = $query->count();

        return $res;
    }

    /**
     * 获取分页列表
     * @param int $page
     * @param $pagesize
     * @param $name
     * @param $account
     * @param $phone
     * @param int $role_id
     * @modify add role_id by milloc 2018-4-27
     * @return array
     */
    public static function getManagerList($page = 0, $pagesize, $name, $account, $phone, $role_id)
    {
        //计算起始数据行
        if ($page <= 0) $page = 0;
        $start = $page * $pagesize;

        // $sql = 'SELECT t1.* FROM t_manager t1
        //         WHERE t1.name LIKE :name AND t1.account LIKE :account AND t1.phone LIKE :phone AND t1.is_deleted = 0
        //         ORDER BY t1.create_datetime DESC
        //         LIMIT :start  ,:pagesize';
        // $cmd = \Yii::$app->db->createCommand($sql);
        // $cmd->bindValue(':name', '%' . $name . '%');
        // $cmd->bindValue(':account', '%' . $account . '%');
        // $cmd->bindValue(':phone', '%' . $phone . '%');
        // $cmd->bindValue(':start', $start);
        // $cmd->bindValue(':pagesize', $pagesize);

        // $result = DbCacheUtility::queryAll($cmd);
        // return $result;

        // 查询角色的时候，先查询角色是否被删除，是返回空
        $manager_query = ManagerDb::find()->where(['is_deleted' => ManagerDb::IS_DELETED_NO])->andFilterWhere(['like', 'name', $name])->andFilterWhere(['like', 'account', $account])->andFilterWhere(['like', 'phone', $phone]);

        if ($role_id) {
            if (Role::find(['id' => $role_id, 'is_deleted' => Role::IS_DELETED_NO])->count()) {
                $manager_query = $manager_query->leftJoin(['re' => ManagerRoleRelation::tableName()], 're.manager_id = id')->andWhere(['re.role_id' => $role_id]);
            } else {
                return [];
            }
        }

        $manager = $manager_query->limit($pagesize)->offset($start)->orderBy('create_datetime desc')->asArray()->all();

        $role_info = [];
        if (!empty($manager)) {
            $manager_id = array_column($manager, 'id');

            $role_info_query = (new Query)->from(['re' => ManagerRoleRelation::tableName()])->leftJoin(['r' => Role::tableName()], 'r.id = re.role_id')->where(['re.manager_id' => $manager_id, 'r.is_deleted' => Role::IS_DELETED_NO])->select(['id' => 're.manager_id','role_id' => 'r.id', 'role_name' => 'r.name', 'role_is_enabled' => 'r.is_enabled']);
            $role_info = $role_info_query->all();
        } else {
            return [];
        }

        $manager_list = [];
        foreach ($manager as $item) {
            $item['role'] = [];
            foreach ($role_info as $key => $value) {
                if ($value['id'] == $item['id']) {
                    unset($value['id']);
                    $item['role'][] = $value;
                    $flag = true;
                    unset($role_info[$key]);
                }
            }
            $manager_list[] = $item;
        }

        return $manager_list;
    }

    /**
     * 根据id获取管理员记录
     * @param $id
     * @modify add role info by milloc 2018-4-28
     * @return array|false
     */
    public static function getManagerById($id)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT t1.* FROM t_manager t1 WHERE t1.id = :id LIMIT 1');
        $cmd->bindValue(':id', $id);

        $item = DbCacheUtility::queryOne($cmd);

        if (!$item) {
            return null;
        }

        $item['role'] = array_column(ManagerRoleRelation::find()->where(['manager_id' => $id])->asArray()->all(), 'role_id');

        return $item;
    }

    /**
     * 判断账户是否存在
     * @param $account
     * @return bool
     */
    public static function existManager($account)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT COUNT(1) FROM t_manager WHERE account = :account AND is_enabled = 1 AND is_deleted = 0');
        $cmd->bindValue(':account', $account);

        $result = DbCacheUtility::queryScalar($cmd);
        return $result > 0;
    }

    public static function chackAccountById($id, $account)
    {
        $sql = 'SELECT COUNT(1) FROM t_manager WHERE id = :id AND account = :account';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':account', $account);
        $result = DbCacheUtility::queryScalar($cmd);

        return $result > 0;
    }

    /**
     * 添加mananger
     * md(password+password_token)
     * @param $id
     * @param $league_id
     * @param $name
     * @param $account
     * @param $phone
     * @param $remark
     * @param $role_id modify by milloc 2018-4-28
     * @return mixed
     */
    public static function saveManager($id, $name, $account, $password, $phone, $remark, $is_enabled, $role_id)
    {
        $transaction = yii::$app->db->beginTransaction();

        $cmd = \Yii::$app->db->createCommand('call p_manager_save(:id,:name,:account,:password,:phone,:remark,:is_enabled)');
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':name', $name);
        $cmd->bindValue(':account', $account);
        $cmd->bindValue(':password', $password);
        $cmd->bindValue(':phone', $phone);
        $cmd->bindValue(':remark', $remark);
        $cmd->bindValue(':is_enabled', $is_enabled);

        $id = DbCacheUtility::queryScalar($cmd);

        $res = $id !== false && ($role_id ?  ManagerRoleRelation::saveManagerRole($id, $role_id) : true);
        if ($res) {
            $transaction->commit();
        } else {
            $transaction->rollBack();
            $id = 0;
        }

        return $id;
    }

    /**
     * 删除mananger
     * @param $id
     * @return bool
     */
    public static function deleteManager($id)
    {
        $cmd = \Yii::$app->db->createCommand('UPDATE t_manager SET is_deleted = 1 WHERE id = :id');
        $cmd->bindValue(':id', $id);

        DbCacheUtility::execute($cmd);
        return true;
    }

    // 管理员修改个人信息
    // add $role_id modify by milloc 2018-4-28
    public static function editManager($id, $name, $phone, $remark, $role_id)
    {
        $transaction = yii::$app->db->beginTransaction();

        $cmd = \Yii::$app->db->createCommand('UPDATE t_manager SET name=:name ,phone=:phone,remark=:remark WHERE id=:id');

        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':name', $name);
        $cmd->bindValue(':phone', $phone);
        $cmd->bindValue(':remark', $remark);
        $result = DbCacheUtility::execute($cmd);

        $res = $result !== false && ($role_id ? ManagerRoleRelation::saveManagerRole($id, $role_id) : true);
        if ($res) {
            $transaction->commit();
        } else {
            $transaction->rollBack();
        }

        return $res;
    }

    public static function validateOldManagerPassword($id, $old_password)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT * FROM t_manager WHERE id = :id AND password = lower(md5(concat(:password,password_token))) AND is_enabled = 1 AND is_deleted = 0');
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':password', $old_password);

        return DbCacheUtility::queryOne($cmd);

    }
    //endregion

    /**
     * 修改密码
     * @param $id
     * @param $password
     * @return bool
     */
    public static function saveManagerPassword($id, $password)
    {
        $cmd = \Yii::$app->db->createCommand('call p_manager_save_password(:id,:password)');
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':password', $password);
        DbCacheUtility::execute($cmd);
        return true;
    }

    /**
     * 验证用户名密码
     * @param $account
     * @param $password
     * @return array|false|null
     */
    public static function validatePassword($account, $password)
    {
        $sql = 'SELECT t1.*
                FROM t_manager t1
                WHERE t1.account = :account 
                    AND t1.password = lower(md5(concat(:password,t1.password_token))) 
                    AND t1.is_enabled = 1 
                    AND t1.is_deleted = 0';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':account', $account);
        $cmd->bindValue(':password', $password);
        $item = DbCacheUtility::queryOne($cmd);

        if($item){
            if($item['account'] == 'admin'){
                $item['mini_programs'] = self::getAdminMiniPrograms();
            }else{
                $item['mini_programs'] = self::getManagerMiniPrograms($item['id']);
            }
        }

        return $item;
    }


    /**
     * 用户登录以后,设置到session中
     * @param $manager
     * @return mixed
     */
    public static function setCurrentManager($manager)
    {
        \Yii::$app->session->remove(self::SessionKey);
        \Yii::$app->session->set(self::SessionKey, $manager);
//        if($rememberMe){
//            \Yii::$app->response->cookies->add(new Cookie([
//                'name' => self::CookieKey,
//                'value' => $manager,
//                'expire' => time() + 3600 * 24 * 7
//            ]));
//        }
        return $manager;
    }

    /**
     * 退出登录
     */
    public static function managerLogout()
    {
        \Yii::$app->session->removeAll();
    }


    public static function getManagerAddMiniPrograms($manager_id)
    {
        $sql = 'SELECT name,id FROM t_mini_programs WHERE id not in (select mini_program_id FROM t_manager_mini_program_relation WHERE manager_id = :manager_id)';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':manager_id', $manager_id);
        $items = DbCacheUtility::queryAll($cmd);

        return $items;
    }

    public static function getManagerDeleteMiniPrograms($manager_id)
    {
        $sql = 'SELECT name,id FROM t_mini_programs WHERE id in (select mini_program_id FROM t_manager_mini_program_relation WHERE manager_id = :manager_id)';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':manager_id', $manager_id);
        $items = DbCacheUtility::queryAll($cmd);

        return $items;
    }

    public static function saveManagerMiniPrograms($manager_id,$mini_program_ids)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        $result = 0;
        try {
            //添加
            if (isset($mini_program_ids) && count($mini_program_ids) > 0) {
                foreach ($mini_program_ids as $mini_program_id) {

                        $cmd = \Yii::$app->db->createCommand('INSERT INTO t_manager_mini_program_relation(id,manager_id,mini_program_id)
                                                              VALUES(UUID(),:manager_id,:mini_program_id)');
                        $cmd->bindValue(':manager_id', $manager_id);
                        $cmd->bindValue(':mini_program_id', $mini_program_id);
                        DbCacheUtility::execute($cmd);
                }
            }
            $transaction->commit();
            $result = 1;
        } catch (\Exception $ex) {
            $transaction->rollBack();
        }
        return $result > 0;
    }

    public static function deleteManagerMiniPrograms($manager_id,$mini_program_ids)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        $result = 0;
        try {
            //添加
            if (isset($mini_program_ids) && count($mini_program_ids) > 0) {
                foreach ($mini_program_ids as $mini_program_id) {

                    $cmd = \Yii::$app->db->createCommand('delete from t_manager_mini_program_relation where manager_id = :manager_id and mini_program_id = :mini_program_id');
                    $cmd->bindValue(':manager_id', $manager_id);
                    $cmd->bindValue(':mini_program_id', $mini_program_id);
                    DbCacheUtility::execute($cmd);
                }
            }
            $transaction->commit();
            $result = 1;
        } catch (\Exception $ex) {
            $transaction->rollBack();
        }
        return $result > 0;
    }


    public static function getAdminMiniPrograms()
    {
        $sql = 'SELECT * FROM t_mini_programs WHERE is_enabled = 1 AND is_deleted = 0';
        $cmd = \Yii::$app->db->createCommand($sql);
        $items = DbCacheUtility::queryAll($cmd);

        return $items;
    }

    public static function getManagerMiniPrograms($manager_id)
    {
        $sql = 'SELECT t1.* FROM t_mini_programs t1 
                    INNER JOIN t_manager_mini_program_relation t2 ON t2.mini_program_id = t1.id
                WHERE t1.is_enabled = 1 AND t1.is_deleted = 0 AND t2.manager_id = :manager_id  ';

        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':manager_id', $manager_id);
        $items = DbCacheUtility::queryAll($cmd);

        return $items;
    }

    public static function isHasMiniProgram($mini_program_id)
    {
        $current_manager_mini_programs = Manager::getCurrentManager()['mini_programs'];
        foreach ($current_manager_mini_programs as $mini_program){
            if($mini_program['id'] == $mini_program_id){
                return true;
            }
        }

        return false;
    }

    /**
     * 查找用户组的用户
     * @param  int $role_id
     * @return array
     * @author milloc
     * @date   2018-04-27
     */
    public static function getManagerListByRoleId($role_id)
    {
        $manager_list = [];
        if ($role_id) {
            $manager_list = (new Query)->from(['r' => ManagerRoleRelation::tableName()])->leftJoin(['m' => ManagerDb::tableName()], 'm.id = r.manager_id')->where(['r.role_id' => $role_id, 'm.is_deleted' => ManagerDb::IS_DELETED_NO, 'm.is_enabled' => ManagerDb::IS_ENABLED_YES])->select(['m.*'])->all();
        }

        return $manager_list;
    }
}